import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoSever {
    private DatagramSocket socket = null;
    public UdpEchoSever(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("启动服务器！");
        while(true){
            //1.读取客户端发来的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);
            //把DatagramPacket解析成一个String
            String request = new String(requestPacket.getData(),0,requestPacket.getLength(),"UTF-8");
            //2.根据请求计算响应
            String response = process(request);
            //3.把响应写回到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(requestPacket);
            System.out.printf("[%s : %d] req: %s, resp: %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }
    //由于是回显服务器，响应和请求一样了
    //实际上对于一个真实的服务器来说。这个过程是最复杂的，为了实现这个过程，可能需要几万行代码，甚至更多
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoSever sever = new UdpEchoSever(8080);
        sever.start();
    }
}
